home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / threading.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  22KB  |  833 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. import sys as _sys
  5.  
  6. try:
  7.     import thread
  8. except ImportError:
  9.     del _sys.modules[__name__]
  10.     raise 
  11.  
  12. from time import time as _time, sleep as _sleep
  13. from traceback import format_exc as _format_exc
  14. from collections import deque
  15. __all__ = [
  16.     'activeCount',
  17.     'Condition',
  18.     'currentThread',
  19.     'enumerate',
  20.     'Event',
  21.     'Lock',
  22.     'RLock',
  23.     'Semaphore',
  24.     'BoundedSemaphore',
  25.     'Thread',
  26.     'Timer',
  27.     'setprofile',
  28.     'settrace',
  29.     'local',
  30.     'stack_size']
  31. _start_new_thread = thread.start_new_thread
  32. _allocate_lock = thread.allocate_lock
  33. _get_ident = thread.get_ident
  34. ThreadError = thread.error
  35. del thread
  36. _VERBOSE = False
  37.  
  38. class _Verbose(object):
  39.     
  40.     def __init__(self, verbose = None):
  41.         pass
  42.  
  43.     
  44.     def _note(self, *args):
  45.         pass
  46.  
  47.  
  48. _profile_hook = None
  49. _trace_hook = None
  50.  
  51. def setprofile(func):
  52.     global _profile_hook
  53.     _profile_hook = func
  54.  
  55.  
  56. def settrace(func):
  57.     global _trace_hook
  58.     _trace_hook = func
  59.  
  60. Lock = _allocate_lock
  61.  
  62. def RLock(*args, **kwargs):
  63.     return _RLock(*args, **kwargs)
  64.  
  65.  
  66. class _RLock(_Verbose):
  67.     
  68.     def __init__(self, verbose = None):
  69.         _Verbose.__init__(self, verbose)
  70.         self._RLock__block = _allocate_lock()
  71.         self._RLock__owner = None
  72.         self._RLock__count = 0
  73.  
  74.     
  75.     def __repr__(self):
  76.         owner = self._RLock__owner
  77.         if owner:
  78.             pass
  79.         return '<%s(%s, %d)>' % (self.__class__.__name__, owner.getName(), self._RLock__count)
  80.  
  81.     
  82.     def acquire(self, blocking = 1):
  83.         me = currentThread()
  84.         if self._RLock__owner is me:
  85.             self._RLock__count = self._RLock__count + 1
  86.             return 1
  87.         
  88.         rc = self._RLock__block.acquire(blocking)
  89.         if rc:
  90.             self._RLock__owner = me
  91.             self._RLock__count = 1
  92.         
  93.         return rc
  94.  
  95.     __enter__ = acquire
  96.     
  97.     def release(self):
  98.         if self._RLock__owner is not currentThread():
  99.             raise RuntimeError('cannot release un-aquired lock')
  100.         
  101.         self._RLock__count = count = self._RLock__count - 1
  102.         if not count:
  103.             self._RLock__owner = None
  104.             self._RLock__block.release()
  105.         
  106.  
  107.     
  108.     def __exit__(self, t, v, tb):
  109.         self.release()
  110.  
  111.     
  112.     def _acquire_restore(self, .1):
  113.         (count, owner) = .1
  114.         self._RLock__block.acquire()
  115.         self._RLock__count = count
  116.         self._RLock__owner = owner
  117.  
  118.     
  119.     def _release_save(self):
  120.         count = self._RLock__count
  121.         self._RLock__count = 0
  122.         owner = self._RLock__owner
  123.         self._RLock__owner = None
  124.         self._RLock__block.release()
  125.         return (count, owner)
  126.  
  127.     
  128.     def _is_owned(self):
  129.         return self._RLock__owner is currentThread()
  130.  
  131.  
  132.  
  133. def Condition(*args, **kwargs):
  134.     return _Condition(*args, **kwargs)
  135.  
  136.  
  137. class _Condition(_Verbose):
  138.     
  139.     def __init__(self, lock = None, verbose = None):
  140.         _Verbose.__init__(self, verbose)
  141.         if lock is None:
  142.             lock = RLock()
  143.         
  144.         self._Condition__lock = lock
  145.         self.acquire = lock.acquire
  146.         self.release = lock.release
  147.         
  148.         try:
  149.             self._release_save = lock._release_save
  150.         except AttributeError:
  151.             pass
  152.  
  153.         
  154.         try:
  155.             self._acquire_restore = lock._acquire_restore
  156.         except AttributeError:
  157.             pass
  158.  
  159.         
  160.         try:
  161.             self._is_owned = lock._is_owned
  162.         except AttributeError:
  163.             pass
  164.  
  165.         self._Condition__waiters = []
  166.  
  167.     
  168.     def __enter__(self):
  169.         return self._Condition__lock.__enter__()
  170.  
  171.     
  172.     def __exit__(self, *args):
  173.         return self._Condition__lock.__exit__(*args)
  174.  
  175.     
  176.     def __repr__(self):
  177.         return '<Condition(%s, %d)>' % (self._Condition__lock, len(self._Condition__waiters))
  178.  
  179.     
  180.     def _release_save(self):
  181.         self._Condition__lock.release()
  182.  
  183.     
  184.     def _acquire_restore(self, x):
  185.         self._Condition__lock.acquire()
  186.  
  187.     
  188.     def _is_owned(self):
  189.         if self._Condition__lock.acquire(0):
  190.             self._Condition__lock.release()
  191.             return False
  192.         else:
  193.             return True
  194.  
  195.     
  196.     def wait(self, timeout = None):
  197.         if not self._is_owned():
  198.             raise RuntimeError('cannot wait on un-aquired lock')
  199.         
  200.         waiter = _allocate_lock()
  201.         waiter.acquire()
  202.         self._Condition__waiters.append(waiter)
  203.         saved_state = self._release_save()
  204.         
  205.         try:
  206.             if timeout is None:
  207.                 waiter.acquire()
  208.             else:
  209.                 endtime = _time() + timeout
  210.                 delay = 0.0005
  211.                 while True:
  212.                     gotit = waiter.acquire(0)
  213.                     if gotit:
  214.                         break
  215.                     
  216.                     remaining = endtime - _time()
  217.                     if remaining <= 0:
  218.                         break
  219.                     
  220.                     delay = min(delay * 2, remaining, 0.05)
  221.                     _sleep(delay)
  222.                 if not gotit:
  223.                     
  224.                     try:
  225.                         self._Condition__waiters.remove(waiter)
  226.                     except ValueError:
  227.                         pass
  228.                     except:
  229.                         None<EXCEPTION MATCH>ValueError
  230.                     
  231.  
  232.                 None<EXCEPTION MATCH>ValueError
  233.         finally:
  234.             self._acquire_restore(saved_state)
  235.  
  236.  
  237.     
  238.     def notify(self, n = 1):
  239.         if not self._is_owned():
  240.             raise RuntimeError('cannot notify on un-aquired lock')
  241.         
  242.         _Condition__waiters = self._Condition__waiters
  243.         waiters = _Condition__waiters[:n]
  244.         if not waiters:
  245.             return None
  246.         
  247.         if not n != 1 or 's':
  248.             pass
  249.         self._note('%s.notify(): notifying %d waiter%s', self, n, '')
  250.         for waiter in waiters:
  251.             waiter.release()
  252.             
  253.             try:
  254.                 _Condition__waiters.remove(waiter)
  255.             continue
  256.             except ValueError:
  257.                 continue
  258.             
  259.  
  260.         
  261.  
  262.     
  263.     def notifyAll(self):
  264.         self.notify(len(self._Condition__waiters))
  265.  
  266.  
  267.  
  268. def Semaphore(*args, **kwargs):
  269.     return _Semaphore(*args, **kwargs)
  270.  
  271.  
  272. class _Semaphore(_Verbose):
  273.     
  274.     def __init__(self, value = 1, verbose = None):
  275.         if value < 0:
  276.             raise ValueError('semaphore initial value must be >= 0')
  277.         
  278.         _Verbose.__init__(self, verbose)
  279.         self._Semaphore__cond = Condition(Lock())
  280.         self._Semaphore__value = value
  281.  
  282.     
  283.     def acquire(self, blocking = 1):
  284.         rc = False
  285.         self._Semaphore__cond.acquire()
  286.         while self._Semaphore__value == 0:
  287.             if not blocking:
  288.                 break
  289.             
  290.             self._Semaphore__cond.wait()
  291.         self._Semaphore__value = self._Semaphore__value - 1
  292.         rc = True
  293.         self._Semaphore__cond.release()
  294.         return rc
  295.  
  296.     __enter__ = acquire
  297.     
  298.     def release(self):
  299.         self._Semaphore__cond.acquire()
  300.         self._Semaphore__value = self._Semaphore__value + 1
  301.         self._Semaphore__cond.notify()
  302.         self._Semaphore__cond.release()
  303.  
  304.     
  305.     def __exit__(self, t, v, tb):
  306.         self.release()
  307.  
  308.  
  309.  
  310. def BoundedSemaphore(*args, **kwargs):
  311.     return _BoundedSemaphore(*args, **kwargs)
  312.  
  313.  
  314. class _BoundedSemaphore(_Semaphore):
  315.     
  316.     def __init__(self, value = 1, verbose = None):
  317.         _Semaphore.__init__(self, value, verbose)
  318.         self._initial_value = value
  319.  
  320.     
  321.     def release(self):
  322.         if self._Semaphore__value >= self._initial_value:
  323.             raise ValueError, 'Semaphore released too many times'
  324.         
  325.         return _Semaphore.release(self)
  326.  
  327.  
  328.  
  329. def Event(*args, **kwargs):
  330.     return _Event(*args, **kwargs)
  331.  
  332.  
  333. class _Event(_Verbose):
  334.     
  335.     def __init__(self, verbose = None):
  336.         _Verbose.__init__(self, verbose)
  337.         self._Event__cond = Condition(Lock())
  338.         self._Event__flag = False
  339.  
  340.     
  341.     def isSet(self):
  342.         return self._Event__flag
  343.  
  344.     
  345.     def set(self):
  346.         self._Event__cond.acquire()
  347.         
  348.         try:
  349.             self._Event__flag = True
  350.             self._Event__cond.notifyAll()
  351.         finally:
  352.             self._Event__cond.release()
  353.  
  354.  
  355.     
  356.     def clear(self):
  357.         self._Event__cond.acquire()
  358.         
  359.         try:
  360.             self._Event__flag = False
  361.         finally:
  362.             self._Event__cond.release()
  363.  
  364.  
  365.     
  366.     def wait(self, timeout = None):
  367.         self._Event__cond.acquire()
  368.         
  369.         try:
  370.             if not self._Event__flag:
  371.                 self._Event__cond.wait(timeout)
  372.         finally:
  373.             self._Event__cond.release()
  374.  
  375.  
  376.  
  377. _counter = 0
  378.  
  379. def _newname(template = 'Thread-%d'):
  380.     global _counter
  381.     _counter = _counter + 1
  382.     return template % _counter
  383.  
  384. _active_limbo_lock = _allocate_lock()
  385. _active = { }
  386. _limbo = { }
  387.  
  388. class Thread(_Verbose):
  389.     __initialized = False
  390.     __exc_info = _sys.exc_info
  391.     
  392.     def __init__(self, group = None, target = None, name = None, args = (), kwargs = None, verbose = None):
  393.         _Verbose.__init__(self, verbose)
  394.         if kwargs is None:
  395.             kwargs = { }
  396.         
  397.         self._Thread__target = target
  398.         if not name:
  399.             pass
  400.         self._Thread__name = str(_newname())
  401.         self._Thread__args = args
  402.         self._Thread__kwargs = kwargs
  403.         self._Thread__daemonic = self._set_daemon()
  404.         self._Thread__started = False
  405.         self._Thread__stopped = False
  406.         self._Thread__block = Condition(Lock())
  407.         self._Thread__initialized = True
  408.         self._Thread__stderr = _sys.stderr
  409.  
  410.     
  411.     def _set_daemon(self):
  412.         return currentThread().isDaemon()
  413.  
  414.     
  415.     def __repr__(self):
  416.         status = 'initial'
  417.         if self._Thread__started:
  418.             status = 'started'
  419.         
  420.         if self._Thread__stopped:
  421.             status = 'stopped'
  422.         
  423.         if self._Thread__daemonic:
  424.             status = status + ' daemon'
  425.         
  426.         return '<%s(%s, %s)>' % (self.__class__.__name__, self._Thread__name, status)
  427.  
  428.     
  429.     def start(self):
  430.         if not self._Thread__initialized:
  431.             raise RuntimeError('thread.__init__() not called')
  432.         
  433.         if self._Thread__started:
  434.             raise RuntimeError('thread already started')
  435.         
  436.         _active_limbo_lock.acquire()
  437.         _limbo[self] = self
  438.         _active_limbo_lock.release()
  439.         _start_new_thread(self._Thread__bootstrap, ())
  440.         self._Thread__started = True
  441.         _sleep(1e-06)
  442.  
  443.     
  444.     def run(self):
  445.         if self._Thread__target:
  446.             self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
  447.         
  448.  
  449.     
  450.     def __bootstrap(self):
  451.         
  452.         try:
  453.             self._Thread__bootstrap_inner()
  454.         except:
  455.             if self._Thread__daemonic and _sys is None:
  456.                 return None
  457.             
  458.             raise 
  459.  
  460.  
  461.     
  462.     def __bootstrap_inner(self):
  463.         
  464.         try:
  465.             self._Thread__started = True
  466.             _active_limbo_lock.acquire()
  467.             _active[_get_ident()] = self
  468.             del _limbo[self]
  469.             _active_limbo_lock.release()
  470.             if _trace_hook:
  471.                 self._note('%s.__bootstrap(): registering trace hook', self)
  472.                 _sys.settrace(_trace_hook)
  473.             
  474.             if _profile_hook:
  475.                 self._note('%s.__bootstrap(): registering profile hook', self)
  476.                 _sys.setprofile(_profile_hook)
  477.             
  478.             
  479.             try:
  480.                 self.run()
  481.             except SystemExit:
  482.                 pass
  483.             except:
  484.                 if _sys:
  485.                     _sys.stderr.write('Exception in thread %s:\n%s\n' % (self.getName(), _format_exc()))
  486.                 else:
  487.                     (exc_type, exc_value, exc_tb) = self._Thread__exc_info()
  488.                     
  489.                     try:
  490.                         print >>self._Thread__stderr, 'Exception in thread ' + self.getName() + ' (most likely raised during interpreter shutdown):'
  491.                         print >>self._Thread__stderr, 'Traceback (most recent call last):'
  492.                         while exc_tb:
  493.                             print >>self._Thread__stderr, '  File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)
  494.                             exc_tb = exc_tb.tb_next
  495.                         print >>self._Thread__stderr, '%s: %s' % (exc_type, exc_value)
  496.                     finally:
  497.                         del exc_type
  498.                         del exc_value
  499.                         del exc_tb
  500.  
  501.  
  502.         finally:
  503.             _active_limbo_lock.acquire()
  504.             
  505.             try:
  506.                 self._Thread__stop()
  507.                 
  508.                 try:
  509.                     del _active[_get_ident()]
  510.                 except:
  511.                     pass
  512.  
  513.             finally:
  514.                 _active_limbo_lock.release()
  515.  
  516.  
  517.  
  518.     
  519.     def __stop(self):
  520.         self._Thread__block.acquire()
  521.         self._Thread__stopped = True
  522.         self._Thread__block.notifyAll()
  523.         self._Thread__block.release()
  524.  
  525.     
  526.     def __delete(self):
  527.         _active_limbo_lock.acquire()
  528.         
  529.         try:
  530.             del _active[_get_ident()]
  531.         except KeyError:
  532.             if 'dummy_threading' not in _sys.modules:
  533.                 raise 
  534.             
  535.         except:
  536.             'dummy_threading' not in _sys.modules
  537.         finally:
  538.             _active_limbo_lock.release()
  539.  
  540.  
  541.     
  542.     def join(self, timeout = None):
  543.         if not self._Thread__initialized:
  544.             raise RuntimeError('Thread.__init__() not called')
  545.         
  546.         if not self._Thread__started:
  547.             raise RuntimeError('cannot join thread before it is started')
  548.         
  549.         if self is currentThread():
  550.             raise RuntimeError('cannot join current thread')
  551.         
  552.         self._Thread__block.acquire()
  553.         
  554.         try:
  555.             if timeout is None:
  556.                 while not self._Thread__stopped:
  557.                     self._Thread__block.wait()
  558.             else:
  559.                 deadline = _time() + timeout
  560.                 while not self._Thread__stopped:
  561.                     delay = deadline - _time()
  562.                     if delay <= 0:
  563.                         break
  564.                     
  565.                     self._Thread__block.wait(delay)
  566.         finally:
  567.             self._Thread__block.release()
  568.  
  569.  
  570.     
  571.     def getName(self):
  572.         return self._Thread__name
  573.  
  574.     
  575.     def setName(self, name):
  576.         self._Thread__name = str(name)
  577.  
  578.     
  579.     def isAlive(self):
  580.         if self._Thread__started:
  581.             pass
  582.         return not (self._Thread__stopped)
  583.  
  584.     
  585.     def isDaemon(self):
  586.         return self._Thread__daemonic
  587.  
  588.     
  589.     def setDaemon(self, daemonic):
  590.         if not self._Thread__initialized:
  591.             raise RuntimeError('Thread.__init__() not called')
  592.         
  593.         if self._Thread__started:
  594.             raise RuntimeError('cannot set daemon status of active thread')
  595.         
  596.         self._Thread__daemonic = daemonic
  597.  
  598.  
  599.  
  600. def Timer(*args, **kwargs):
  601.     return _Timer(*args, **kwargs)
  602.  
  603.  
  604. class _Timer(Thread):
  605.     
  606.     def __init__(self, interval, function, args = [], kwargs = { }):
  607.         Thread.__init__(self)
  608.         self.interval = interval
  609.         self.function = function
  610.         self.args = args
  611.         self.kwargs = kwargs
  612.         self.finished = Event()
  613.  
  614.     
  615.     def cancel(self):
  616.         self.finished.set()
  617.  
  618.     
  619.     def run(self):
  620.         self.finished.wait(self.interval)
  621.         if not self.finished.isSet():
  622.             self.function(*self.args, **self.kwargs)
  623.         
  624.         self.finished.set()
  625.  
  626.  
  627.  
  628. class _MainThread(Thread):
  629.     
  630.     def __init__(self):
  631.         Thread.__init__(self, name = 'MainThread')
  632.         self._Thread__started = True
  633.         _active_limbo_lock.acquire()
  634.         _active[_get_ident()] = self
  635.         _active_limbo_lock.release()
  636.  
  637.     
  638.     def _set_daemon(self):
  639.         return False
  640.  
  641.     
  642.     def _exitfunc(self):
  643.         self._Thread__stop()
  644.         t = _pickSomeNonDaemonThread()
  645.         if t:
  646.             pass
  647.         
  648.         while t:
  649.             t.join()
  650.             t = _pickSomeNonDaemonThread()
  651.         self._Thread__delete()
  652.  
  653.  
  654.  
  655. def _pickSomeNonDaemonThread():
  656.     for t in enumerate():
  657.         if not t.isDaemon() and t.isAlive():
  658.             return t
  659.             continue
  660.     
  661.  
  662.  
  663. class _DummyThread(Thread):
  664.     
  665.     def __init__(self):
  666.         Thread.__init__(self, name = _newname('Dummy-%d'))
  667.         del self._Thread__block
  668.         self._Thread__started = True
  669.         _active_limbo_lock.acquire()
  670.         _active[_get_ident()] = self
  671.         _active_limbo_lock.release()
  672.  
  673.     
  674.     def _set_daemon(self):
  675.         return True
  676.  
  677.     
  678.     def join(self, timeout = None):
  679.         pass
  680.  
  681.  
  682.  
  683. def currentThread():
  684.     
  685.     try:
  686.         return _active[_get_ident()]
  687.     except KeyError:
  688.         return _DummyThread()
  689.  
  690.  
  691.  
  692. def activeCount():
  693.     _active_limbo_lock.acquire()
  694.     count = len(_active) + len(_limbo)
  695.     _active_limbo_lock.release()
  696.     return count
  697.  
  698.  
  699. def enumerate():
  700.     _active_limbo_lock.acquire()
  701.     active = _active.values() + _limbo.values()
  702.     _active_limbo_lock.release()
  703.     return active
  704.  
  705. from thread import stack_size
  706. _shutdown = _MainThread()._exitfunc
  707.  
  708. try:
  709.     from thread import _local as local
  710. except ImportError:
  711.     from _threading_local import local
  712.  
  713.  
  714. def _after_fork():
  715.     global _active_limbo_lock
  716.     _active_limbo_lock = _allocate_lock()
  717.     new_active = { }
  718.     current = currentThread()
  719.     _active_limbo_lock.acquire()
  720.     
  721.     try:
  722.         for thread in _active.itervalues():
  723.             if thread is current:
  724.                 ident = _get_ident()
  725.                 thread._Thread__ident = ident
  726.                 new_active[ident] = thread
  727.                 continue
  728.             thread._Thread__stopped = True
  729.         
  730.         _limbo.clear()
  731.         _active.clear()
  732.         _active.update(new_active)
  733.     finally:
  734.         _active_limbo_lock.release()
  735.  
  736.  
  737.  
  738. def _test():
  739.     
  740.     class BoundedQueue(_Verbose):
  741.         
  742.         def __init__(self, limit):
  743.             _Verbose.__init__(self)
  744.             self.mon = RLock()
  745.             self.rc = Condition(self.mon)
  746.             self.wc = Condition(self.mon)
  747.             self.limit = limit
  748.             self.queue = deque()
  749.  
  750.         
  751.         def put(self, item):
  752.             self.mon.acquire()
  753.             while len(self.queue) >= self.limit:
  754.                 self._note('put(%s): queue full', item)
  755.                 self.wc.wait()
  756.             self.queue.append(item)
  757.             self._note('put(%s): appended, length now %d', item, len(self.queue))
  758.             self.rc.notify()
  759.             self.mon.release()
  760.  
  761.         
  762.         def get(self):
  763.             self.mon.acquire()
  764.             while not self.queue:
  765.                 self._note('get(): queue empty')
  766.                 self.rc.wait()
  767.             item = self.queue.popleft()
  768.             self._note('get(): got %s, %d left', item, len(self.queue))
  769.             self.wc.notify()
  770.             self.mon.release()
  771.             return item
  772.  
  773.  
  774.     
  775.     class ProducerThread(Thread):
  776.         
  777.         def __init__(self, queue, quota):
  778.             Thread.__init__(self, name = 'Producer')
  779.             self.queue = queue
  780.             self.quota = quota
  781.  
  782.         
  783.         def run(self):
  784.             random = random
  785.             import random
  786.             counter = 0
  787.             while counter < self.quota:
  788.                 counter = counter + 1
  789.                 self.queue.put('%s.%d' % (self.getName(), counter))
  790.                 _sleep(random() * 1e-05)
  791.  
  792.  
  793.     
  794.     class ConsumerThread(Thread):
  795.         
  796.         def __init__(self, queue, count):
  797.             Thread.__init__(self, name = 'Consumer')
  798.             self.queue = queue
  799.             self.count = count
  800.  
  801.         
  802.         def run(self):
  803.             while self.count > 0:
  804.                 item = self.queue.get()
  805.                 print item
  806.                 self.count = self.count - 1
  807.  
  808.  
  809.     NP = 3
  810.     QL = 4
  811.     NI = 5
  812.     Q = BoundedQueue(QL)
  813.     P = []
  814.     for i in range(NP):
  815.         t = ProducerThread(Q, NI)
  816.         t.setName('Producer-%d' % (i + 1))
  817.         P.append(t)
  818.     
  819.     C = ConsumerThread(Q, NI * NP)
  820.     for t in P:
  821.         t.start()
  822.         _sleep(1e-06)
  823.     
  824.     C.start()
  825.     for t in P:
  826.         t.join()
  827.     
  828.     C.join()
  829.  
  830. if __name__ == '__main__':
  831.     _test()
  832.  
  833.